package org.simp.codec;


import org.apache.log4j.Logger;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.simp.core.body.RouteBody;
import org.simp.core.head.Header;
import org.simp.core.message.SimpMessageWraper;

/**
 * @author zhuhaitao at 2014-5-22
 *
 * SIMP 请求解码器
 */
public class SimpRequestDecoder extends CumulativeProtocolDecoder {

	private static final Logger log = Logger.getLogger(SimpRequestDecoder.class);
	@Override
	protected boolean doDecode(IoSession session, IoBuffer buffer,
			ProtocolDecoderOutput out) throws Exception {
		int headLength = buffer.getInt();
		if(buffer.remaining() < headLength){
			log.debug(" recivice data length less than headLength,data is error ");
			return false;
		}
		SimpMessageWraper simpMsg = new SimpMessageWraper();
		
		byte [] headData = new byte[headLength];
		buffer.get(headData);
		Header header = new Header();
		header.decode(headData);
		simpMsg.setHead(header);
		int contentLength = header.getContentLength();
		/**数据长度不够时，返回等待**/
		if(buffer.remaining() < contentLength){
			log.debug(" data length less than expected");
			buffer.rewind();
			return false;
		}
		log.debug(String.format(" RECEIVE DATA  : FROM %1$s TO %2$s ,MSG CODE : %3$s %4$s",simpMsg.getHead().getSrcAddress(),simpMsg.getHead().getObjAddress(),simpMsg.getHead().getMainId(),simpMsg.getHead().getMoudleId()));
		/**如果有消息体，先不解析，后面根据情况，分发或者解析**/
		if(contentLength >0){
			byte[] bodyData = new byte[contentLength];
			buffer.get(bodyData);
			RouteBody body = new RouteBody();
			body.decode(bodyData);
			simpMsg.setBody(body);
		}
		
		out.write(simpMsg);
		
		return true;
	}

}
